/**
 * @Author: lena
 * @Description:http client端操作
 * @Version: 1.0.0
 * @Date: 2021/9/11 15:17
 */

package http

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

// Client1 接收响应信息
func Client1() {
	// 发送get请求 :func Get(url string) (resp *Response, err error)
	resp, err := http.Get("http://127.0.0.1:9000/hello/world")
	if err != nil {
		fmt.Println("[client] get err:", err)
		return
	}
	// 读取响应信息
	all, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("[client] read err:", err)
		return
	}
	fmt.Println(string(all)) // <h1>helloworld</h1>
}

// Client2 当请求参数有特殊含义字符(如?)时需要转义
func Client2() {
	// 添加参数
	param := url.Values{}
	param.Set("a", "!!!???")
	param.Set("b", "你好啊")
	//param.Set("c","@$#@%")
	paramEncode := param.Encode()                 // 编码
	fmt.Println("[client] enconde:", paramEncode) // [client] enconde: a=%21%21%21%3F%3F%3F&b=%E4%BD%A0%E5%A5%BD%E5%95%8A
	// 解析url
	url, err := url.Parse("http://127.0.0.1:9000/hello/world")
	if err != nil {
		fmt.Println("[client] parse err :", err)
		return
	}
	// 加入参数到url
	url.RawQuery = paramEncode
	fmt.Println("[client] url.string :", url.String()) // url.string : http://127.0.0.1:9000/hello/world?a=%21%21%21%3F%3F%3F&b=%E4%BD%A0%E5%A5%BD%E5%95%8A
	// 发送请求
	resp, err := http.Get(url.String())
	if err != nil {
		fmt.Println("[client] request err :", err)
		return
	}
	defer resp.Body.Close()
	// 读取响应信息
	all, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("[client] read err:", err)
		return
	}
	fmt.Println("[client]", string(all)) // a=!!!???,b=你好啊

}

// Client3 发送post请求
func Client3() {
	url := "http://127.0.0.1:9000/post"
	// 设置请求头和form表单数据
	contentType := "application/json"
	data := `{"name":"lena","wechat":"777"}`
	// 发送请求
	post, err := http.Post(url, contentType, strings.NewReader(data))
	if err != nil {
		fmt.Println("[client] post err :", err)
		return
	}
	defer post.Body.Close()
	// 接收响应
	all, err := ioutil.ReadAll(post.Body)
	if err != nil {
		fmt.Println("[client] read response err :", err)
		return
	}
	fmt.Println("[client] response :", string(all)) // [client] response : {"status":"1"}
}
